package cn.gcjlearn.websocketdemo.websockethandler;

import cn.gcjlearn.websocketdemo.vo.JsonResultWebSocket;
import cn.gcjlearn.websocketdemo.vo.SendMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
@Component
@ServerEndpoint("/chat")
public class ChatWebSocket {
    private String username;

    /*存放所有人的session*/
    private static Map<String, Session> mapSessions = new HashMap<>();

    /*存放所有人的账户名*/
    private static List<String> usernames = new ArrayList<>();

    @OnOpen
    public void open(Session session) throws IOException {
        /*获取参数栏中“？”后所有的信息*/
        String queryString = session.getQueryString();
        username = queryString.split("=")[1];

        /*添加用户列表*/
        this.usernames.add(username);

        /*连接的会话添加到会话集合中*/
        mapSessions.put(username,session);

        //json结果封装
        JsonResultWebSocket jrw = new JsonResultWebSocket();
        jrw.setType(0);
        jrw.setContent("欢迎进入聊天室："+username);
        jrw.setUsernames(usernames);
        jrw.setDate(new Date());

        this.boradcast(mapSessions,this.ObjectToJSONString(jrw));
    }
    
    @OnMessage
    public void message(Session session , String msg) throws IOException {
        Map<String, Session> toSessions = null;

        ObjectMapper om = new ObjectMapper();
        SendMessage sendMessage = om.readValue(msg, SendMessage.class);

        JsonResultWebSocket jrw = new JsonResultWebSocket();
        jrw.setType(2);
        jrw.setFrom(username);
        jrw.setContent("输入的内容："+sendMessage.getMsg());
        jrw.setDate(new Date());

        if(sendMessage.getType() == 1){
            //发送给所有人
            toSessions = mapSessions;
        }else{
            //获取发送指定的人
            toSessions = getToSessions(sendMessage.getTo());
        }

        this.boradcast(toSessions,this.ObjectToJSONString(jrw));
    }

    @OnClose
    public void close(Session session) throws IOException {
        /*移除当前退出的用户信息*/
        usernames.remove(username);
        mapSessions.remove(username);

        //json结果封装
        JsonResultWebSocket jrw = new JsonResultWebSocket();
        jrw.setType(0);
        jrw.setContent(username+"，退出聊天室：");
        jrw.setUsernames(usernames);
        jrw.setDate(new Date());
        this.boradcast(mapSessions,this.ObjectToJSONString(jrw));
    }


    /*传递给指定的人*/
    private void boradcast(Map<String, Session> mapSessions, String msg) throws IOException {
        for(String key:mapSessions.keySet()){
            try{
                Session session = mapSessions.get(key);
                session.getBasicRemote().sendText(msg);
            }catch (Exception e){}
        }
    }

    /*获取名称对应的Session*/
    private Map<String, Session> getToSessions(String[] toNames){
        Map<String, Session> toSessions = new HashMap<>();
        for(String name : toNames){
            toSessions.put(name,this.mapSessions.get(name));
        }
        return toSessions;
    }

    /*将Object对象转换成JSON数据*/
    private String ObjectToJSONString(Object ob) throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        return om.writeValueAsString(ob);
    }
}
